#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/10 20:51
# @Author  : Tina.du
# @File    : robot.py
# @Project description：
import json
import urllib
import requests
import time
import hmac
import hashlib
import base64
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class Ding:
    """
    钉钉机器人
    """

    def __init__(self):
        # CPB测试群-钉钉机器人的webhook地址
        self.url = 'https://oapi.dingtalk.com/robot/send?access_token=99c023ce10c158555e37652edf496e1992614423785bf05597f57f0d0a5c04d1'
        # secret
        self.secret = 'SECe162267e9241924924240b23b0879ccfd48b3c3a7b00513c51d6c0851863c4b7'

    def check_secret(self, secret):
        """
        生成secret加签
        :param secret:
        :return:
        """
        timestamp = str(round(time.time() * 1000))
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        return "&timestamp=" + timestamp + "&sign=" + sign

    def send_message(self, message=None):
        """
        发送钉钉消息
        :param message: 发送内容
        :return:
        """
        test_url = self.url + self.check_secret(f"{self.secret}")

        headers = {
            "Content-Type": "application/json;charset=utf-8"
        }

        message = message
        string_text_msg = {
            "msgtype": "text",
            "text": {"content": message},
            "at": {
                "isAtAll": 1  # 如果需要@所有人，这些写1
            }
        }
        string_text_msg = json.dumps(string_text_msg)
        with requests.post(test_url, data=string_text_msg, headers=headers, verify=False) as res:
            return res

    def send_link(self, message_url):
        """
        发送钉钉链接
        :param message_url: 指定的url
        :return:
        """
        test_url = self.url + self.check_secret(f"{self.secret}")

        headers = {
            "Content-Type": "application/json;charset=utf-8"
        }

        string_link_msg = {
            "msgtype": "link",
            "link": {
                "text": "今天吃点啥呢？去悠饭看看吧～",
                "title": "悠饭点饭啦～",
                "picUrl": "https://tvax4.sinaimg.cn/crop.0.0.891.891.180/006Gos8ply8fxgn9viu2fj30ot0orgna.jpg?KID=imgbed,tva&Expires=1626279933&ssig=dsK87pjAuN",
                "messageUrl": message_url
            }
        }
        string_text_msg = json.dumps(string_link_msg)
        with requests.post(test_url, data=string_text_msg, headers=headers, verify=False) as res:
            return res
